package com.shioirikukuri.controller;

import com.shioirikukuri.common.until.RedisUtil;
import com.shioirikukuri.redisinfo.AdminInfo;
import com.shioirikukuri.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/admin")
public class AdminController {

	/**
	 * token 过期时间，单位：秒,延长30min
	 */
	private static final long TOKEN_EXPIRE_TIME = 1800L;

	@Autowired
	private IAdminService adminService;

	@Autowired
	private RedisUtil redisUtil;

	/**
	 *
	 * 管理员或前台服务员登录
     *
	 * @param request 包含 phoneNumber, password, role 的 JSON 对象
     * @return 包含 token 的响应体（成功）或错误信息（失败）
	 **/
	@PostMapping("/login")
	public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> request) {
		try {
			// 调用返回 token 的 Service 方法
			String token = adminService.login(
					request.get("phoneNumber"),
					request.get("password"),
					request.get("role")
			);

			// 构造标准响应格式：token 放在 data 字段中
			Map<String, Object> response = new HashMap<>();
			response.put("code", HttpStatus.OK.value());
			response.put("data", Collections.singletonMap("token", token));
			response.put("message", "登录成功");
			return ResponseEntity.ok(response);

		} catch (Exception e) {
			// 统一错误响应格式
			Map<String, Object> errorResponse = new HashMap<>();
			errorResponse.put("code", HttpStatus.UNAUTHORIZED.value());
			errorResponse.put("message", e.getMessage());
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorResponse);
		}
	}

	/**
	 * 管理员或前台服务员登出
	 * @param token
	 * @return
	 */
	@PostMapping("/logout")
	public ResponseEntity<?> logout(@RequestHeader("Authorization") String token) {
		String redisKey = "session:" + token;
		redisUtil.delete(redisKey);
		return ResponseEntity.ok().build();
	}

	/**
	 * 检查 token 是否有效
	 * @param token
	 * @return
	 */
	@PostMapping("/checkToken")
	public ResponseEntity<?> checkToken(@RequestHeader("Authorization") String token) {
		String redisKey = "session:" + token;
		boolean exists = redisUtil.hasKey(redisKey);
		if (exists) {
			redisUtil.expire(redisKey, TOKEN_EXPIRE_TIME, TimeUnit.SECONDS); // 例如延长至2小时
		}
		Map<String, Object> response = new HashMap<>();
		response.put("code", exists ? HttpStatus.OK.value() : HttpStatus.UNAUTHORIZED.value());
		response.put("message", exists ? "Token有效" : "Token无效或已过期");
		return ResponseEntity.status(exists ? HttpStatus.OK : HttpStatus.UNAUTHORIZED).body(response);
	}

	/**
	 * 获取Redis中存储的管理员信息
	 *
	 * @param token
	 * @return 管理员信息
	 */
	@GetMapping("/getAdminInfo")
	public ResponseEntity<Map<String, Object>> getAdminInfo(@RequestHeader("Authorization") String token) {
		// 直接使用 token 作为 key
		String redisKey = token;

		try {
			AdminInfo adminInfo = redisUtil.get(redisKey, AdminInfo.class);

			if (adminInfo == null) {
				Map<String, Object> errorResponse = new HashMap<>();
				errorResponse.put("code", HttpStatus.UNAUTHORIZED.value());
				errorResponse.put("message", "Token无效或管理员信息不存在");
				return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorResponse);
			}

			redisUtil.expire(redisKey, TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);

			Map<String, Object> response = new HashMap<>();
			response.put("code", HttpStatus.OK.value());
			response.put("data", adminInfo);
			response.put("message", "管理员信息获取成功");

			return ResponseEntity.ok(response);

		} catch (Exception e) {
			Map<String, Object> errorResponse = new HashMap<>();
			errorResponse.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
			errorResponse.put("message", "服务器内部错误：" + e.getMessage());
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
		}
	}

}
